package com.code2roc.fastboot.framework.security;

import com.alibaba.fastjson.JSON;
import com.code2roc.fastboot.framework.util.CommonUtil;
import com.code2roc.fastboot.framework.util.DESEncryptUtil;
import com.code2roc.fastboot.framework.util.RSAEncryptUtil;
import com.code2roc.fastboot.framework.util.StringUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Aspect
@Component
@Order(value = 85)
public class EncryptDataTransferAspect {

    /**
     * 切面点 指定注解
     */
    @Pointcut("@annotation(org.springframework.web.bind.annotation.PostMapping) " +
            "|| @within(org.springframework.web.bind.annotation.PostMapping)" +
            "@annotation(org.springframework.web.bind.annotation.GetMapping) " +
            "|| @within(org.springframework.web.bind.annotation.GetMapping)")
    public void encryptDataTransferAspect() {

    }

    /**
     * 拦截方法指定为 repeatSubmitAspect
     */
    @Around("encryptDataTransferAspect()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        Object result = null;
        try {
            result = point.proceed();
            HttpServletRequest request = CommonUtil.getRequest();
            String encrypt = request.getHeader("encrypt");
            if (!StringUtil.isEmpty(encrypt)) {
                String privateKey = RSAEncryptUtil.getSystemDefaultRSAPrivateKey();
                String desEncryptStr = RSAEncryptUtil.decryptPKSC1(encrypt, privateKey);
                result = DESEncryptUtil.encrypt(JSON.toJSONStringWithDateFormat(result, "yyyy-MM-dd HH:mm:ss"), desEncryptStr);
            }
        } catch (Exception e) {

        }
        return result;
    }
}
